package com.itheima.utils;

import com.itheima.loginMapper.UserMapper;
import jdk.nashorn.internal.ir.GetSplitState;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;

/**
 * @Author: yg
 * @create 2025-02-07 - 22:00
 * @
 */
public class MyBatisUtils {

    public static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public static <T> T getMapper(Class<T> mapperClass){
        SqlSession session = sqlSessionFactory.openSession();
        return session.getMapper(mapperClass);
    }

    public static void closeSession(Object mapper){
        SqlSession session = GetSqlSessionFromMapper(mapper);
        if (session != null){
            session.close();
        }
    }

    public static SqlSession GetSqlSessionFromMapper(Object mapper) {
        try {
            Field sqlSessionField = mapper.getClass().getDeclaredField("sqlSession");
            sqlSessionField.setAccessible(true);
            return (SqlSession) sqlSessionField.get(mapper);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
